
package com.huanxun.foodspath3;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.huanxun.bean.MsgDetailBean_Purchaser;
import com.huanxun.bean.MsgDetailBean_Purchaser.DataEntityPurchaser;
import com.huanxun.bean.MsgDetailBean_Purchaser.DataEntityPurchaser.FactoryProcessArrayListEntity;
import com.huanxun.bean.MsgDetailBean_Purchaser.DataEntityPurchaser.PortInfoList;
import com.huanxun.utils.Constants;
import com.huanxun.utils.MLogger;
import com.huanxun.utils.SystemUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;

/**
 * 采购商 下单详情.
 *
 */
public class MsgDetail_buyer extends Activity implements OnClickListener {
	
	@ViewInject(R.id.tv_date)
	private TextView tv_date;
	@ViewInject(R.id.view_line)
	private View view_line;
	@ViewInject(R.id.bt_order)
	private Button bt_order;
	@ViewInject(R.id.ll_notify2)
	private LinearLayout ll_notify2;
	@ViewInject(R.id.ll_frame)
	private LinearLayout ll_frame;
	@ViewInject(R.id.rl2)
	private RelativeLayout rl2;
	@ViewInject(R.id.ll_choice_port)
	private LinearLayout ll_choice_port;
	@ViewInject(R.id.tv_port_choice)
	private TextView tv_port_choice;
	
	
	
	private int ChoiceNumber=-1;
	private ListView lv_content;
	private TextView tv_msgdetail_title;
	private MAdapter mAdapter;
	private ImageView iv_msgdetail_back;
	
	private String id;
	private String title;
	private String time;
	private String[] mportList;
	
	private ArrayList<String> strs;
	private ArrayList<String> strs2;
	private ArrayList<String> strs3;
	private ArrayList<String> strs4;
	private ArrayList<String> strs5;
	private ArrayList<String> strs6;
	private ArrayList<String> strs7;
	private ListView lv_package1;
	private M2Adapter m2Adapter;
	private DataEntityPurchaser data2;
	
	private List<FactoryProcessArrayListEntity> factoryProcessArrayList;
	private List<PortInfoList> portInfoList2;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_msgdetail_buyer);
		
		getData();
		ViewUtils.inject(this);
		LoadMsgListData();
		
	}

	private void LoadMsgListData() {
	 	String path=Constants.URL_MSG_DETAIL_BUYER;
	 	MLogger.i("Url_Buyer_Detail", path+id);
		SystemUtils.httpUtils.send(HttpMethod.GET,path+id, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String result = responseInfo.result;
				MLogger.i("Buyer_Detail", result);
				processData(result);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				MLogger.i("Buyer_Detail", "failed");
				runOnUiAlert("网络错误");
			}
		});
	}


	protected void processData(String result) {
		MsgDetailBean_Purchaser msgDetailBean = SystemUtils.gson.fromJson(result, MsgDetailBean_Purchaser.class);
		if("fail".equals(msgDetailBean.msg)){
			SystemUtils.toast(getApplicationContext(), "数据加载失败");
			finish();
		}else{
			strs3=new ArrayList<String>();
			strs4=new ArrayList<String>();
			strs5=new ArrayList<String>();
			strs6=new ArrayList<String>();
			strs7=new ArrayList<String>();
			data2 = msgDetailBean.data;
			List<String> qualifications = data2.qualifications;
			factoryProcessArrayList = data2.factoryProcessArrayList;
			long deliveryTime = data2.deliveryTime;
			String changeTimeFormat = SystemUtils.changeTimeFormat(deliveryTime);
			portInfoList2 = data2.portInfoList;
			
			for (int i = 0; i < data2.portInfoList.size(); i++) {
				 PortInfoList portInfoList = data2.portInfoList.get(i);
				 strs3.add(portInfoList.portName);
				if(i==0){
					addPortName(strs4,portInfoList);
				}else if(i==1){
					addPortName(strs5,portInfoList);
				}else if(i==2){
					addPortName(strs6,portInfoList);
				}else{
					addPortName(strs7,portInfoList);
				}
			}
			mportList = (String[]) strs3.toArray(new String[data2.portInfoList.size()]);
			for (int i = 0; i < data2.factoryProcessArrayList.size(); i++) {
				 FactoryProcessArrayListEntity factoryProcessArrayListEntity = data2.factoryProcessArrayList.get(i);
				 if(i==0){
				addProcess(strs4,factoryProcessArrayListEntity);
				 }else if(i==1){
				addProcess(strs5,factoryProcessArrayListEntity);
				 }else if(i==2){
				addProcess(strs6,factoryProcessArrayListEntity);
				 }else{
				addProcess(strs7,factoryProcessArrayListEntity);
				 }
				
			}
			
			
			strs=new ArrayList<String>();
			strs2=new ArrayList<String>();
			
			
			strs.add("公司名称:   ");
			strs2.add(data2.companyName);
			strs.add("官方评价:   ");
			strs2.add(data2.evaluate);
			strs.add("用户好评:   ");
			strs2.add(data2.highOpinion);
			strs.add("产品大类:   ");
			strs2.add(data2.bigTypeName);
			strs.add("产品小类:   ");
			strs2.add(data2.middleTypeName);
			strs.add("产品名称:   ");
			strs2.add(data2.typeName);
			strs.add("发货时间:   ");
			strs2.add(changeTimeFormat);
			strs.add("付款方式:   ");
			strs2.add(data2.paymentType);
			strs.add("运输方式:   ");
			strs2.add(data2.transportType);
			strs.add("资质要求:   ");
			StringBuilder temp = new StringBuilder();
			for (int i = 0; i < qualifications.size(); i++) {
				String string = qualifications.get(i);
				if(qualifications.size()-1==i){
					temp.append(string);}
				else{	
				temp.append(string+" ; ");}
			}
			String ab = temp.toString();
			strs2.add(ab);
		initView();
		}
	}

	private void addPortName(ArrayList<String> strs88, PortInfoList portInfoList) {
		strs88.add("发货港　:   "+portInfoList.portName);
	}

	private void addProcess(
			ArrayList<String> strs, FactoryProcessArrayListEntity factoryProcessArrayListEntity) {
		strs.add("包装工艺:   "+factoryProcessArrayListEntity.packageProcessName);
		strs.add("产品工艺:   "+factoryProcessArrayListEntity.productProcessName);
		strs.add("价　　格:   "+factoryProcessArrayListEntity.price+"");
		strs.add("总　　量:   "+factoryProcessArrayListEntity.amount+"");
	}

	private void initView() {
		ScrollView sv = (ScrollView) findViewById(R.id.sv);
		sv.smoothScrollTo(0, 0);
		rl2.setVisibility(View.GONE);
		interfaceDisplay();
		
		iv_msgdetail_back = (ImageView) findViewById(R.id.iv_msgdetail_back);
		iv_msgdetail_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		tv_msgdetail_title = (TextView) findViewById(R.id.tv_msgdetail_title);
		
		tv_msgdetail_title.setText(title);
		tv_date.setText(time);
		
		lv_content = (ListView) findViewById(R.id.lv_content);
		lv_package1 = (ListView) findViewById(R.id.lv_package1);

		mAdapter = new MAdapter();
		lv_content.setAdapter(mAdapter);
		m2Adapter = new M2Adapter();
		lv_package1.setAdapter(m2Adapter);
		
		bt_order.setOnClickListener(this);
		ll_choice_port.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				displayDiaglog();
			}
		});
	}
	
private void interfaceDisplay() {
	tv_date.setVisibility(View.VISIBLE);
	view_line.setVisibility(View.VISIBLE);
	bt_order.setVisibility(View.VISIBLE);
	ll_notify2.setVisibility(View.VISIBLE);
	ll_frame.setBackgroundResource(R.drawable.edit_text_bg2);
	}
	
	/*
	 * 其中包括港口相关信息  及  数量加减的button.
	 */
	private class M2Adapter extends BaseAdapter{

		
		@Override
		public int getCount() {
			
			return data2.portInfoList.size();
		}

		@Override
		public Object getItem(int position) {
			
			return null;
		}

		@Override
		public long getItemId(int position) {
			
			
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
				View view  =View.inflate(MsgDetail_buyer.this, R.layout.item_msgdetail_buyer_package, null);
				ListView lv_process_technology_buyer = (ListView) view.findViewById(R.id.lv_process_technology_buyer);
				TextView tv_count_minus2 = (TextView) view.findViewById(R.id.tv_count_minus2);
				final TextView tv_count = (TextView) view.findViewById(R.id.tv_count);
				TextView tv_count_plus = (TextView) view.findViewById(R.id.tv_count_plus);
				
				tv_count_minus2.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						String string = tv_count.getText().toString();
						long parseLong = Long.parseLong(string);
						if(parseLong<=0){
							SystemUtils.toast(MsgDetail_buyer.this, "下单数量不可小于0!");
							return;
						}
							parseLong--;
						tv_count.setText(parseLong+"");
					}
				});
				
				tv_count_plus.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(ChoiceNumber!=position){
							View childAt = lv_package1.getChildAt(position);
							TextView tv_count = (TextView) childAt.findViewById(R.id.tv_count);
							tv_count.setText("0");
							SystemUtils.toast(MsgDetail_buyer.this, "请选择匹配的港口下单!");
							return;
						}
						String string = tv_count.getText().toString();
						long parseLong = Long.parseLong(string);
							parseLong++;
						tv_count.setText(parseLong+"");
					}
				});
				
				
				/*将此listView中的item的positon传递给下一个ListView*/
				M5Adapter m5Adapter = new M5Adapter(position);
				lv_process_technology_buyer.setAdapter(m5Adapter);
			return view;
		}
	
	/*其中包括港口相关信息   不包括数量加减的button*/
	private class M5Adapter extends BaseAdapter{
		/*获取上个ListView(M2Adapter)传递item的positon位置,根据此positon的值.来为新的LivewView(M5Adapter)
		    适配器Adapter确定匹配的数据源. 
		 */
		public int count;
		public M5Adapter(int position) {
			this.count=position;
		}

		@Override
		public int getCount() {
			if(count==0){
				return strs4.size();
			}else if(count==1){
				return strs5.size();
			}else if(count==2){
				return strs6.size();
			}else {
				return strs7.size();
			}
		}

		@Override
		public Object getItem(int position) {
			
			return null;
		}

		@Override
		public long getItemId(int position) {
			
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = View.inflate(MsgDetail_buyer.this, R.layout.item_buyer_proceess_tech, null);
			TextView tv_buyer_process_technology = (TextView) view.findViewById(R.id.tv_buyer_process_technology);
			
			String str="";
			if(count==0){
				str=strs4.get(position);
			}else if(count==1){
				str=strs5.get(position);
			}else if(count==2){
				str=strs6.get(position);
			}else{
				str=strs7.get(position);
			}
			tv_buyer_process_technology.setText(str);
			return view;
		}
		
	}


		
	}
	
	private class MAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			
			return strs.size();
		}

		@Override
		public Object getItem(int position) {
			
			return strs.get(position);	
		}

		@Override
		public long getItemId(int position) {
			
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view =null;
			ViewHolder holder =null;
			if(convertView==null){
				view =View.inflate(MsgDetail_buyer.this, R.layout.item_msgdetail_buyer, null);
				holder = new ViewHolder();
				holder.tv_paragraph = (TextView) view.findViewById(R.id.tv_paragraph);
				holder.tv_paragraph2 = (TextView) view.findViewById(R.id.tv_paragraph2);
				view.setTag(holder);
			}else{
				view=convertView;	
				holder= (ViewHolder) view.getTag();
			}
			
			String a = strs.get(position);
			String b = strs2.get(position);
			holder.tv_paragraph.setText(a);
			holder.tv_paragraph2.setText(b);
			return view;
		}
		
	}
	
	static class ViewHolder{
		TextView tv_paragraph;
		TextView tv_paragraph2;
		
	}
	private void getData() {
		Intent intent = getIntent();
		title = intent.getStringExtra("title");
		time = intent.getStringExtra("time");
		id = intent.getStringExtra("id");
	}
	private String packageProcessId3 ="";
	private String portId3 ="";
	private String amount3="0";
	
	/*
	 * 下单按钮点击事件.
	 */
	@Override
	public void onClick(View v) {
	
		String port = tv_port_choice.getText().toString();
		
		if(port.contains("未选择")){
			SystemUtils.toast(MsgDetail_buyer.this, "请先选择港口!");
		}else
		{
				for (int i = 0; i < data2.portInfoList.size(); i++) {
					String portName = data2.portInfoList.get(i).portName;
					if(port.contains(portName)){
						matchSubmitInfo(i);
					}
				}
				if("0".equals(amount3)){
					SystemUtils.toast(MsgDetail_buyer.this, "下单数量不可为0!");
					return;
				}
			new Thread(){
				public void run() {
					String urlPath = "http://112.126.80.199:9990/foodspath/v02/order/purchase/";
					URL url;
					JSONObject jsonObject = new JSONObject();
					JSONObject jsonObject2 = new JSONObject();
					JSONArray array = new JSONArray();
					try {
						url=new URL(urlPath);
						jsonObject.put("productId", data2.productId);
						jsonObject.put("portId", portId3);
						jsonObject2.put("processArrayId",packageProcessId3);
						jsonObject2.put("amount",amount3);
						array.put(jsonObject2);
						jsonObject.put("purchaseProcessNecessaryList", array);
						
						String content2 = jsonObject.toString();
						
						MLogger.i("OrderInfo_Buyer", content2);
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						conn.setConnectTimeout(5000);
						// 设置允许输出
						conn.setDoOutput(true);
						conn.setRequestMethod("POST");
						// 设置User-Agent: Fiddler
						conn.setRequestProperty("ser-Agent", "Fiddler");
						// 设置contentType
						conn.setRequestProperty("Content-Type", "application/json");
						OutputStream os = conn.getOutputStream();
						os.write(content2.getBytes());
						os.close();
						//服务器返回的响应码
						int code = conn.getResponseCode();
						MLogger.i("Code_Buyer_response", code+"");
						if (code == 200) {
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									for (int i = 0; i < lv_package1.getChildCount(); i++) {
										View childAt = lv_package1.getChildAt(i);
										TextView tv_count = (TextView) childAt.findViewById(R.id.tv_count);
										tv_count.setText("0");
									}
									
								}
							});
							
							runOnUiAlert("下单成功!");
							
							InputStream is = conn.getInputStream();
							String json = com.huanxun.engine.NetUtils.readBytes(is);
							
							MLogger.i("Server_response_Buyer", json);
							JSONObject jsonObject3 = new JSONObject(json);
							String string = jsonObject3.getString("msg");
							MLogger.i("Server_response_Buyer", string);	
					} else{
						runOnUiAlert("下单失败!");
					}
				}catch (Exception e) {
					runOnUiAlert("请检查网络!");
					e.printStackTrace();
				}
					
				}

			}.start();
			
		
	}
	}


	private void runOnUiAlert(final String text) {
		runOnUiThread(new Runnable() {
		
		@Override
		public void run() {
			Toast.makeText(MsgDetail_buyer.this, text, Toast.LENGTH_SHORT).show();
		}
	});
};

	private void displayDiaglog(){
		new AlertDialog.Builder(MsgDetail_buyer.this).setTitle("请选择")
		.setIcon(android.R.drawable.ic_dialog_info)
		.setSingleChoiceItems(mportList,ChoiceNumber, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				ChoiceNumber=which;
			}
		}).setNegativeButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				which=ChoiceNumber;
				if(which>=0){
					String string = mportList[ChoiceNumber];
					for (int i = 0; i < lv_package1.getChildCount(); i++) {
						View childAt = lv_package1.getChildAt(i);
						TextView tv_count = (TextView) childAt.findViewById(R.id.tv_count);
						tv_count.setText("0");
					}
					tv_port_choice.setText("   "+string);
				}else{
					SystemUtils.toast(MsgDetail_buyer.this, "请选择港口");
				}
				
			}
		}).setPositiveButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		}).show();
	}
	
	public void matchSubmitInfo(int position){
		View childAt = lv_package1.getChildAt(position);
		TextView tv_count = (TextView) childAt.findViewById(R.id.tv_count);
		amount3= tv_count.getText().toString();
		FactoryProcessArrayListEntity factoryProcessArrayListEntity = factoryProcessArrayList.get(position);
		packageProcessId3 = factoryProcessArrayListEntity.packageProcessId;
		PortInfoList portInfoList = portInfoList2.get(position);
		portId3 = portInfoList.portId;
		
	}
	
}
